package cn.demo.mvc.service;

import cn.demo.mvc.mapper.AuthorMapper;
import cn.demo.mvc.model.Author;
import cn.demo.mvc.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class AuthorService {

    public List<Author> listAuthors(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class);
        List<Author> authors = mapper.listAuthors();
        return authors;
    }
    public List<Author> searchAuthor(String name){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class);
        List<Author> authors = mapper.searchAuthor(name);
        return authors;
    }
    public boolean addAuthor(Author author){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class);
        int updateRows = mapper.addAuthor(author);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }
    public boolean updateAuthor(Author author){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class);
        int updateRows = mapper.updateAuthor(author);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }
    public boolean deleteAuthorById(int id){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class);
        int updateRows = mapper.deleteAuthorById(id);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }
    @Test
    public void testService() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();

        AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class);

//        mapper.addAuthor(new Author("ttt","@9999999qq.com"));
//        mapper.updateAuthor(new Author(11,"tt2","22@qq.com"));
//        mapper.deleteAuthorById(11);
        sqlSession.commit();
        List<Author> authors = mapper.searchAuthor("book");
//        List<Author> authors = mapper.listAuthors();
        for (Author author : authors) {
            System.out.println(author);
        }
        sqlSession.close();
    }
}
